package tools;


public class URLDecode {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}

	public static String urlDecode(String str) {
		String context = str;
		// 将所有%25，转为%，递归直至没有%25
		try {
			while (context.contains("%25")) {
				context = context.replace("%25", "%");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 将所有codeChars中的字符串，替换为transCodeChars中对应的字符串
		String[] codeChars = { "%20", "%21", "%22", "%23", "%24", "%25", "%26",
				"%27", "%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F",
				"%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%5B", "%5C", "%5D",
				"%5E", "%5F", "%7B", "%7C", "%7D" };
		String[] transCodeChars = { " ", "!", "\"", "#", "$", "%", "&", "'",
				"(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=",
				">", "?", "[", "\\", "]", "^", "_", "{", "|", "}" };
		try {
			context = replaceAllChars(context, codeChars, transCodeChars);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return context;
	}

	/***
	 * 将所有codeChars中的字符串，替换为transCodeChars中对应的字符串
	 * ***/
	public static String replaceAllChars(String str, String[] codeChars,
			String[] transCodeChars) {
		String context = str;

		try {
			if (str == null || codeChars == null || transCodeChars == null
					|| (codeChars.length != transCodeChars.length)) {
				return null;
			}
			for (int i = 0; i < codeChars.length; i++) {
				context = context.replace(codeChars[i], transCodeChars[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return context;
	}

}
